env_logger
Implements a logger that can be configured via environment variables.
Usage
In libraries
env_logger
makes sense when used in executables (binary projects). Libraries should use the log
crate instead.
In executables
It must be added along with log
to the project dependencies:
[]
= "0.4.0"
= "0.9.0"
env_logger
must be initialized as early as possible in the project. After it's initialized, you can use the log
macros to do actual logging.
extern crate log;
Then when running the executable, specify a value for the RUST_LOG
environment variable that corresponds with the log messages you want to show.
The letter case is not significant for the logging level names; e.g., debug
,
DEBUG
, and dEbuG
all represent the same logging level. Therefore, the
previous example could also have been written this way, specifying the log
level as INFO
rather than as info
:
So which form should you use? For consistency, our convention is to use lower case names. Where our docs do use other forms, they do so in the context of specific examples, so you won't be surprised if you see similar usage in the wild.
The log levels that may be specified correspond to the log::Level
enum from the log
crate. They are:
error
warn
info
debug
trace
There is also a pseudo logging level, off
, which may be specified to disable
all logging for a given module or for the entire application. As with the
logging levels, the letter case is not significant.
env_logger
can be configured in other ways besides an environment variable. See the examples for more approaches.
In tests
Tests can use the env_logger
crate to see log messages generated during that test:
[]
= "0.4.0"
[]
= "0.9.0"
extern crate log;
Assuming the module under test is called my_lib
, running the tests with the
RUST_LOG
filtering to info messages from this module looks like:
; ; ;
Note that env_logger::try_init()
needs to be called in each test in which you
want to enable logging. Additionally, the default behavior of tests to
run in parallel means that logging output may be interleaved with test output.
Either run tests in a single thread by specifying RUST_TEST_THREADS=1
or by
running one test by specifying its name as an argument to the test binaries as
directed by the cargo test
help docs:
; ; ;
Configuring log target
By default, env_logger
logs to stderr. If you want to log to stdout instead,
you can use the Builder
to change the log target:
use env;
use ;
let mut builder = from_default_env;
builder.target;
builder.init;
Stability of the default format
The default format won't optimise for long-term stability, and explicitly makes no guarantees about the stability of its output across major, minor or patch version bumps during 0.x
.
If you want to capture or interpret the output of env_logger
programmatically then you should use a custom format.